/*
 * Copyright (C) 2016  SamuelGjk <samuel.alva@outlook.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.ecy.quadratic.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.AppCompatSeekBar;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ecy.quadratic.R;
import com.ecy.quadratic.activity.gallery.GalleryPagerAdapter;
import com.ecy.quadratic.adapter.ComicSectionDetailAdapter;
import com.ecy.quadratic.adapter.ComicSectionsReadAdapter;
import com.ecy.quadratic.beans.ComicSectionDetail;
import com.ecy.quadratic.beans.ComicSectionDetailResponseBean;
import com.ecy.quadratic.beans.SectionBean;
import com.ecy.quadratic.beans.Sections;
import com.ecy.quadratic.component.DaggerComicReadComponent;
import com.ecy.quadratic.manager.SettingManager;
import com.ecy.quadratic.reader.base.BaseActivity;
import com.ecy.quadratic.reader.base.Constant;
import com.ecy.quadratic.reader.component.AppComponent;
import com.ecy.quadratic.reader.utils.ScreenUtils;
import com.ecy.quadratic.reader.utils.SharedPreferencesUtil;
import com.ecy.quadratic.reader.utils.ToastUtils;
import com.ecy.quadratic.reader.view.recyclerview.decoration.DividerDecoration;
import com.ecy.quadratic.request.BasicRequest;
import com.ecy.quadratic.request.ComicSectionDetailRequest;
import com.ecy.quadratic.ui.contract.ComicReadContract;
import com.ecy.quadratic.ui.presenter.ComicReadPresenter;
import com.ecy.quadratic.widget.ComicReadCallback;
import com.ecy.quadratic.widget.HackyViewPager;
import com.ecy.quadratic.widget.LFooter;
import com.ecy.quadratic.widget.RecyclerViewDetector;
import com.ecy.quadratic.widget.RoundImageView;
import com.ecy.quadratic.widget.ScrollGridView;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;

//import com.liulishuo.filedownloader.util.FileDownloadUtils;

/**
 * Created by SamuelGjk on 2016/4/20.
 */
public class ComicReadActivity extends BaseActivity implements ComicReadContract.View, ComicReadCallback, LFooter.FooterListener {
    public static final String COMIC_ID = "comic_read_detail";
    public static final String COMIC_TITLE = "comic_title";
    public static final String COMIC_COVER = "comic_cover";
    public static final String COMIC_SECTIONS = "comic_sections";
    public static final String COMIC_SECTIONBEAN = "comic_sectionbean";
    private final String TAG = "ComicReadActivity";
    private final int NOT_FULL_SCREEN_FLAG = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;

    //    public static final String GALLERY_CMOIC_ID = "GALLERY_CMOIC_ID";
//    public static final String GALLERY_CMOIC_FIRST_LETTER = "GALLERY_CMOIC_FIRST_LETTER";
//    public static final String GALLERY_CHAPTER_LIST = "GALLERY_CHAPTER_LIST";
//    public static final String GALLERY_CHAPTER_POSITION = "GALLERY_CHAPTER_POSITION";
//    public static final String GALLERY_BROWSE_POSITION = "GALLERY_BROWSE_POSITION";
//    public static final String GALLERY_COMIC_TITLE = "GALLERY_COMIC_TITLE";
    private final int FULL_SCREEN_FLAG = NOT_FULL_SCREEN_FLAG | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
    @Bind(R.id.gallery_pager)
    HackyViewPager galleryPager;
    @Bind(R.id.seek_bar)
    AppCompatSeekBar mReadingPostionSeekBar;
    @Bind(R.id.total_pages)
    AppCompatTextView totalPages;
    @Bind(R.id.content_recyclerview)
    LRecyclerView mRecyclerView;
    @Bind(R.id.ivBack)
    ImageView mIvBack;
    @Bind(R.id.tvBookReadIntroduce)
    TextView mTvBookReadChangeSource;
    @Bind(R.id.tvBookReadSource)
    TextView mTvBookReadSource;
    @Bind(R.id.llBookReadTop)
    LinearLayout mLlBookReadTop;
    @Bind(R.id.tvBookReadTocTitle)
    TextView mTvBookReadTocTitle;
    @Bind(R.id.tvComicOrientationMode)
    TextView mTvOrientationMode;
    @Bind(R.id.tvBookReadSettings)
    TextView mTvBookReadSettings;
    @Bind(R.id.tvBookReadDownload)
    TextView mTvBookReadDownload;
    @Bind(R.id.tvBookReadToc)
    TextView mTvBookReadToc;
    @Bind(R.id.llBookReadBottom)
    LinearLayout mLlBookReadBottom;
    @Bind(R.id.rlComicReadRoot)
    RelativeLayout mRlBookReadRoot;
    @Bind(R.id.tvDownloadProgress)
    TextView mTvDownloadProgress;
    @Bind(R.id.ll_comic_read_sections)
    LinearLayout mLlSections;
    @Bind(R.id.comicread_sections_gridview)
    ScrollGridView mGvSections;
    @Bind(R.id.riv_night)
    RoundImageView mToggleDayNightImageView;
    @Bind(R.id.rlReadAaSet)
    LinearLayout rlReadAaSet;
    @Bind(R.id.ivBrightnessMinus)
    ImageView ivBrightnessMinus;
    @Bind(R.id.seekbarLightness)
    SeekBar seekbarLightness;
    @Bind(R.id.ivBrightnessPlus)
    ImageView ivBrightnessPlus;
    @Bind(R.id.atv_vertical_pages)
    AppCompatTextView atvVerticalPages;
    @Bind(R.id.atv_horizontal_pages)
    AppCompatTextView atvHorizontalPages;
    @Bind(R.id.ll_comic_read_mode)
    LinearLayout llComicReadMode;
    @Bind(R.id.cbVolume)
    CheckBox cbVolume;
    @Inject
    ComicReadPresenter mPresenter;
    DividerDecoration itemDecoration;
    boolean isFirst = true;
    private ComicSectionsReadAdapter mComicSectionsAdapter;
    private GalleryPagerAdapter mPagerAdapter;
    private ComicSectionDetailAdapter mComicAdapter;
    private LRecyclerViewAdapter mAdapter;
    private String mComicCover;
    private String mComicId;
    private String mComicTitle;
    private List<SectionBean> mSections;
    private SectionBean mSectionBean;
    //    private String mComicTitle;
//    private String mComicId;
//    private String firstLetter;
//    private List<SectionBean> mChapters;
//    private int mCurChapterPosition;
    private int mLastChapterPosition;
    private int mHistoryBrowsePosition;
    private int intCurPage;
    private Handler mHandler;
    private Runnable mPreviousRunnable, mNextRunnable;
    private boolean useHistory = true;
    private int curTheme = -1;
    private View decodeView;

    private int mCurrSectionPosition = 0;
    private int mPrePostion = 0;
    private int mNextPostion = 0;

    public static void startActivity(Context context, String comicId, String comicTitle, String comicCover, Sections sections, SectionBean currentSectionBean) {
        Intent intent = new Intent(context, ComicReadActivity.class);
        intent.putExtra(COMIC_ID, comicId);
        intent.putExtra(COMIC_TITLE, comicTitle);
        intent.putExtra(COMIC_COVER, comicCover);
        intent.putExtra(COMIC_SECTIONS, sections);
        intent.putExtra(COMIC_SECTIONBEAN, currentSectionBean);
        context.startActivity(intent);
    }

//    @Override
//    public void showMessageSnackbar(int resId) {
//        SnackbarUtils.showShort(galleryPager, resId);
//    }


//    @Override
//    public void loadError() {
//        galleryPager.setCurrentItem(intCurPage < 1 ? 1 : intCurPage);
//        mCurChapterPosition = mLastChapterPosition;
//
//        if (mPagerAdapter.getCount() == 3) {
//            loadErrorLayout.setVisibility(View.VISIBLE);
//        } else {
//            galleryPager.setLocked(false);
//            mReadingPostionSeekBar.setEnabled(true);
//        }
//    }

//    private void fetchChapterContent(String chapterId) {
//        // @formatter:off
////        presenter.updateReadHistory(mComicId, chapterId);
//
//        String url = GComicApi.getInstance().generateDownloadUrl(firstLetter, mComicId, chapterId);
//        String path = DownloadTasksManager.getInstance(this).generatePath(url);
//        int id = FileDownloadUtils.generateId(url, path);
//
//        if (DownloadTasksManager.getInstance(this).isExist(path) && DownloadTasksManager.getInstance(this).isDownloadedById(id)) {
//            presenter.fetchPicturesFromDisk(path);
//        } else {
//            presenter.fetchChapterDetails(mComicId, chapterId);
//        }
//    }

//    public void toggleSystemUi() {
//        boolean isShown = mToolbar.getAlpha() == 1.0f;
//        ViewCompat.animate(mToolbar)
//                  .alpha(isShown ? 0.0f : 1.0f)
//                  .start();
//        ViewCompat.animate(bottomBar)
//                  .alpha(isShown ? 0.0f : 1.0f)
//                  .setListener(new ViewPropertyAnimatorListenerAdapter() {
//                      @Override
//                      public void onAnimationStart(View view) {
//                          super.onAnimationStart(view);
//
//                          if (view.isShown()) {
//                              return;
//                          }
//
//                          view.setVisibility(View.VISIBLE);
//                      }
//
//                      @Override
//                      public void onAnimationEnd(View view) {
//                          super.onAnimationEnd(view);
//
//                          if (view.getAlpha() == 1.0f) {
//                              return;
//                          }
//
//                          view.setVisibility(View.INVISIBLE);
//                      }
//                  })
//                  .start();
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            mDecorView.setSystemUiVisibility(isShown ? FULL_SCREEN_FLAG : NOT_FULL_SCREEN_FLAG);
//        }
//    }

    public void getUrl(String imgUrl) {
        String absoluteUrl = "http://fuciyuanbang.biaoqingdou.com/fuciyuan/v1/pics/" + imgUrl + "?plat=ar&ver=1.4.0.0&uid=866401021740231&sid=&channel=xiaomi&app=FuCiYuan&iscover=false&loginuid=";
        HashMap<String, String> params = new HashMap<>();
        new ComicSectionDetailRequest(params, absoluteUrl).execute(new BasicRequest.OnResponseListener<ComicSectionDetailResponseBean>() {
            @Override
            public void onSuccess(ComicSectionDetailResponseBean comicSectionDetailResponseBean, HashMap<String, String> requestParams) {
                ArrayList<String> urls = new ArrayList<String>();
                if (comicSectionDetailResponseBean == null || comicSectionDetailResponseBean.getResult() == null) {
                    Toast.makeText(ComicReadActivity.this, "null", Toast.LENGTH_SHORT).show();
                }
                mPresenter.saveReadingSection(mComicId, mComicTitle, mComicCover, mSectionBean);

                for (int i = 0; i < comicSectionDetailResponseBean.getResult().size(); i++) {
                    urls.add(comicSectionDetailResponseBean.getResult().get(i).url);
                }
//                updatePagerContent(urls,null,false);
            }

            @Override
            public void onFailed(HashMap<String, String> requestParams) {

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();

//        presenter.updateReadHistory(mComicId, mChapters.get(mCurChapterPosition).chapterId, intCurPage);
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacks(mPreviousRunnable);
        mHandler.removeCallbacks(mNextRunnable);
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        super.onDestroy();
    }

    @Override
    public int getLayoutId() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        statusBarColor = ContextCompat.getColor(this, R.color.reader_menu_bg_color);
        return R.layout.activity_comic_read;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerComicReadComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void initToolBar() {

    }

    @Override
    public void initData() {
        Intent intent = getIntent();

        mComicId = intent.getStringExtra(COMIC_ID);
        mComicTitle = intent.getStringExtra(COMIC_TITLE);
        mComicCover = intent.getStringExtra(COMIC_COVER);
        mSections = (List<SectionBean>) intent.getSerializableExtra(COMIC_SECTIONS);
        mSectionBean = (SectionBean) intent.getSerializableExtra(COMIC_SECTIONBEAN);
        mCurrSectionPosition = 0;
        for (int i = 0; i < mSections.size(); i++) {
            if (mSectionBean.getChapter_id().equals(mSections.get(i).getChapter_id())) {
                mCurrSectionPosition = i;
                break;
            }
        }
        mPrePostion = mCurrSectionPosition - 1;
        mNextPostion = mCurrSectionPosition + 1;
        mComicSectionsAdapter = new ComicSectionsReadAdapter(this, mSections);
    }

    @Override
    public void configViews() {
        hideStatusBar();
        boolean isPortrait = SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_ISPORTRAIT, true);
        if (isPortrait) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        initAASet();
        decodeView = getWindow().getDecorView();

        mComicAdapter = new ComicSectionDetailAdapter(this, new ArrayList<String>(), null, this);

        final RecyclerViewDetector detector = new RecyclerViewDetector(this);
        detector.setComicReadCallback(this);
        final LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setInitialPrefetchItemCount(5);
        mRecyclerView.setLayoutManager(llm);
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });

        itemDecoration = new DividerDecoration(ContextCompat.getColor(this, R.color.black), ScreenUtils.dpToPxInt(4), 0, 0);
        itemDecoration.setDrawLastItem(false);
        itemDecoration.setDrawHeaderFooter(false);
        mRecyclerView.addItemDecoration(itemDecoration);

        mGvSections.setAdapter(mComicSectionsAdapter);
        mGvSections.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSectionBean = mSections.get(position);
                mCurrSectionPosition = position;
                mPrePostion = mCurrSectionPosition - 1;
                mNextPostion = mCurrSectionPosition + 1;
                mPresenter.getImageUrl(mSectionBean, false);
                hideReadBar();
            }
        });

        mAdapter = new LRecyclerViewAdapter(mComicAdapter);

        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLoadMoreEnabled(false);
        mRecyclerView.setPullRefreshEnabled(false);
        LFooter footer = new LFooter(this);
        footer.setFooterListener(this);
        mAdapter.addFooterView(footer);

//        mPagerAdapter = new GalleryPagerAdapter(getSupportFragmentManager());
//        galleryPager.setAdapter(mPagerAdapter);
//        galleryPager.setLocked(true);
//        galleryPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                mReadingPostionSeekBar.setProgress(position);
//
////                intCurPage = position;
////                if (intCurPage > mPagerAdapter.getCount() - 2) {
////                    intCurPage = mPagerAdapter.getCount() - 2;
////                } else if (intCurPage < 1) {
////                    intCurPage = 1;
////                }
////                curPage.setText(String.valueOf(intCurPage));
//
////                if (position == 0) {
////                    galleryPager.setLocked(true);
////                    seekBar.setEnabled(false);
////                    mHandler.postDelayed(mPreviousRunnable, 1000);
////                } else if (position == mPagerAdapter.getCount() - 1) {
////                    galleryPager.setLocked(true);
////                    seekBar.setEnabled(false);
////                    mHandler.postDelayed(mNextRunnable, 1000);
////                }
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
        mReadingPostionSeekBar = (AppCompatSeekBar) findViewById(R.id.seek_bar);
        totalPages = (AppCompatTextView) findViewById(R.id.total_pages);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) bottomBar.getLayoutParams();
//            lp.setMargins(0, 0, 0, Utils.getNavigationBarHeight(this));
//        }

        mHandler = new Handler();
        mReadingPostionSeekBar.setProgress(0);
        mReadingPostionSeekBar.setKeyProgressIncrement(1);
        mReadingPostionSeekBar.setEnabled(false);
        mReadingPostionSeekBar.setKeyProgressIncrement(1);
        mReadingPostionSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            int progress = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                progress = i;
                totalPages.setText(progress + 1 + "/" + mComicAdapter.getItemCount());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                llm.scrollToPositionWithOffset(progress + mAdapter.getHeaderViewsCount() + 1, 0);
//                mRecyclerView.scrollToPosition(progress + mAdapter.getHeaderViewsCount() + 1);
//                galleryPager.setCurrentItem(progress, false);
            }
        });
        mPresenter.attachView(this);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int progress = llm.findLastVisibleItemPosition() - (mAdapter.getHeaderViewsCount() + 1);
                mReadingPostionSeekBar.setProgress(progress);
                totalPages.setText(progress + 1 + "/" + mComicAdapter.getItemCount());
            }
        });
//        getUrl(mSectionBean.getPiclisturl());
        mPresenter.getImageUrl(mSectionBean, false);
        mTvBookReadTocTitle.setText(mComicTitle);
    }

    private void initAASet() {
//        curTheme = SettingManager.getInstance().getReadTheme();
//        ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);

        seekbarLightness.setMax(100);
        seekbarLightness.setOnSeekBarChangeListener(new SeekBarChangeListener());
        int brightness = SettingManager.getInstance().getComicReadBrightness();
        seekbarLightness.setProgress(brightness);
        boolean isNight = SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_ISNIGHT, false);
        if (!isNight) {
            ScreenUtils.setScreenBrightness(brightness, ComicReadActivity.this);
            mToggleDayNightImageView.setImageResource(R.drawable.moon);
        } else {
            ScreenUtils.setScreenBrightness(15, ComicReadActivity.this);
            mToggleDayNightImageView.setImageResource(R.drawable.sun);
        }

//        boolean isVerticalMode = SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_VERTICAL_MODE,true);
//        boolean isPortrait = SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_ISPORTRAIT, true);
//        if(isVerticalMode) {
//            atvVerticalPages.setBackgroundResource(R.drawable.comic_read_mode_pressed);
//            atvHorizontalPages.setBackgroundResource(R.drawable.comic_read_mode_default);
//            atvVerticalPages.setTextColor(Color.parseColor("#83c326"));
//            atvHorizontalPages.setTextColor(Color.WHITE);
//            mRecyclerView.setVisibility(View.VISIBLE);
//            galleryPager.setVisibility(View.GONE);
//            if (!isPortrait) {
//                llComicReadMode.setVisibility(View.GONE);
//            }
//        } else {
//            atvVerticalPages.setBackgroundResource(R.drawable.comic_read_mode_default);
//            atvHorizontalPages.setBackgroundResource(R.drawable.comic_read_mode_pressed);
//            atvVerticalPages.setTextColor(Color.WHITE);
//            atvHorizontalPages.setTextColor(Color.parseColor("#83c326"));
//            if (isPortrait) {
//                mRecyclerView.setVisibility(View.GONE);
//                galleryPager.setVisibility(View.VISIBLE);
//            } else {
//                mRecyclerView.setVisibility(View.VISIBLE);
//                galleryPager.setVisibility(View.GONE);
//                llComicReadMode.setVisibility(View.GONE);
//            }
//
//        }
        cbVolume.setChecked(SettingManager.getInstance().isSystemBrightness());
        cbVolume.setOnCheckedChangeListener(new ChechBoxChangeListener());
    }

    @OnClick(R.id.atv_vertical_pages)
    public void onVerticalModePages() {
        boolean isVerticalMode = SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_VERTICAL_MODE, true);
        if (!isVerticalMode) {
            atvVerticalPages.setBackgroundResource(R.drawable.comic_read_mode_pressed);
            atvHorizontalPages.setBackgroundResource(R.drawable.comic_read_mode_default);
            atvVerticalPages.setTextColor(Color.parseColor("#83c326"));
            atvHorizontalPages.setTextColor(Color.WHITE);
            mRecyclerView.setVisibility(View.VISIBLE);
            galleryPager.setVisibility(View.GONE);
            SharedPreferencesUtil.getInstance().putBoolean(Constant.COMIC_VERTICAL_MODE, true);
        }
    }

    @OnClick(R.id.atv_vertical_pages)
    public void onHorizontalModePages() {
        boolean isVerticalMode = SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_VERTICAL_MODE, true);
        if (isVerticalMode) {
            atvVerticalPages.setBackgroundResource(R.drawable.comic_read_mode_default);
            atvHorizontalPages.setBackgroundResource(R.drawable.comic_read_mode_pressed);
            atvVerticalPages.setTextColor(Color.WHITE);
            atvHorizontalPages.setTextColor(Color.parseColor("#83c326"));
            mRecyclerView.setVisibility(View.GONE);
            galleryPager.setVisibility(View.VISIBLE);
            SharedPreferencesUtil.getInstance().putBoolean(Constant.COMIC_VERTICAL_MODE, false);
        }
    }

    @OnClick(R.id.ivBack)
    public void onClickBack() {
        finish();
//        if (mTocListPopupWindow.isShowing()) {
//            mTocListPopupWindow.dismiss();
//        } else {
//            finish();
//        }
    }

    private synchronized void hideReadBar() {
        gone(mTvDownloadProgress, mLlBookReadBottom, mLlBookReadTop, rlReadAaSet, mLlSections, mToggleDayNightImageView);
//        hideStatusBar();
//        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    }

    private synchronized void showReadBar() { // 显示工具栏
        visible(mLlBookReadBottom, mLlBookReadTop, mToggleDayNightImageView);
//        showStatusBar();
//        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    private synchronized void toggleReadBar() { // 切换工具栏 隐藏/显示 状态
        if (isVisible(mLlBookReadTop)) {
            hideReadBar();
        } else {
            showReadBar();
        }
    }

    /***************Bottom Bar*****************/
    @OnClick(R.id.tvComicOrientationMode)
    public void onClickOrientationMode() { // 日/夜间模式切换
        gone(rlReadAaSet, mLlSections);

        boolean isPortrait = !SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_ISPORTRAIT, true);
        SharedPreferencesUtil.getInstance().putBoolean(Constant.COMIC_ISPORTRAIT, isPortrait);
        if (isPortrait) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }


//    @OnClick(R.id.tvBookReadMode)
//    public void onClickChangeMode() { // 日/夜间模式切换
//        gone(rlReadAaSet, rlReadMark);
//
//        boolean isNight = !SharedPreferencesUtil.getInstance().getBoolean(Constant.ISNIGHT, false);
//        changedMode(isNight, -1);
//    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        hideReadBar();
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTvOrientationMode.setText("竖屏");
//            mRecyclerView.setVisibility(View.VISIBLE);
//            galleryPager.setVisibility(View.GONE);
//            llComicReadMode.setVisibility(View.VISIBLE);
        } else {
            mTvOrientationMode.setText("横屏");
//            llComicReadMode.setVisibility(View.GONE);
//            boolean isVerticalMode = SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_VERTICAL_MODE,true);
//            if(isVerticalMode) {
//                mRecyclerView.setVisibility(View.VISIBLE);
//                galleryPager.setVisibility(View.GONE);
//            } else {
//                mRecyclerView.setVisibility(View.GONE);
//                galleryPager.setVisibility(View.VISIBLE);
//            }

        }
        mComicAdapter.notifyDataSetChanged();
    }

    private void changedMode(boolean isNight, int position) {
        SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, isNight);
        AppCompatDelegate.setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_YES
                : AppCompatDelegate.MODE_NIGHT_NO);

//        if (position >= 0) {
//            curTheme = position;
//        } else {
//            curTheme = SettingManager.getInstance().getReadTheme();
//        }

        mTvOrientationMode.setText(getString(isNight ? R.string.book_read_mode_day_manual_setting
                : R.string.book_read_mode_night_manual_setting));
        Drawable drawable = ContextCompat.getDrawable(this, isNight ? R.drawable.ic_menu_mode_day_manual
                : R.drawable.ic_menu_mode_night_manual);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mTvOrientationMode.setCompoundDrawables(null, drawable, null, null);

//        ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);
    }

    @OnClick(R.id.tvBookReadSettings)
    public void setting() {
        if (isVisible(mLlBookReadBottom)) {
            gone(mLlSections);
            if (isVisible(rlReadAaSet)) {
                gone(rlReadAaSet);
            } else {
                visible(rlReadAaSet);
            }
        }
    }

    @OnClick(R.id.riv_night)
    public void toggleDayNight() {
        boolean isNight = !SharedPreferencesUtil.getInstance().getBoolean(Constant.COMIC_ISNIGHT, false);
        if (isNight) {
            ScreenUtils.setScreenBrightness(15, ComicReadActivity.this);
            mToggleDayNightImageView.setImageResource(R.drawable.sun);
        } else {
            ScreenUtils.setScreenBrightness(SettingManager.getInstance().getComicReadBrightness(), ComicReadActivity.this);
            mToggleDayNightImageView.setImageResource(R.drawable.moon);
        }
        SharedPreferencesUtil.getInstance().putBoolean(Constant.COMIC_ISNIGHT, isNight);
    }

    @OnClick(R.id.tvBookReadDownload)
    public void downloadBook() {
        gone(rlReadAaSet, mLlSections);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("缓存多少章？")
                .setItems(new String[]{"后面五十章", "后面全部", "全部"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
//                            case 0:
//                                DownloadBookService.post(new DownloadQueue(bookId, mChapterList, currentChapter + 1, currentChapter + 50));
//                                break;
//                            case 1:
//                                DownloadBookService.post(new DownloadQueue(bookId, mChapterList, currentChapter + 1, mChapterList.size()));
//                                break;
//                            case 2:
//                                DownloadBookService.post(new DownloadQueue(bookId, mChapterList, 1, mChapterList.size()));
//                                break;
                            default:
                                break;
                        }
                    }
                });
        builder.show();
    }

    @OnClick(R.id.tvBookReadToc)
    public void onClickToc() {
        gone(rlReadAaSet);
        if (isVisible(mLlSections)) {
            gone(mLlSections);
        } else {
            visible(mLlSections);
        }
    }

    /***************Setting Menu*****************/

    @OnClick(R.id.ivBrightnessMinus)
    public void brightnessMinus() {
        int curBrightness = SettingManager.getInstance().getComicReadBrightness();
        if (curBrightness > 2) {
            seekbarLightness.setProgress((curBrightness = curBrightness - 2));
            cbVolume.setChecked(false);
            ScreenUtils.setScreenBrightness(curBrightness, ComicReadActivity.this);
            SettingManager.getInstance().saveComicReadBrightness(curBrightness);
        }
    }

    @OnClick(R.id.ivBrightnessPlus)
    public void brightnessPlus() {
        int curBrightness = SettingManager.getInstance().getComicReadBrightness();
        if (curBrightness < 99) {
            seekbarLightness.setProgress((curBrightness = curBrightness + 2));
            cbVolume.setChecked(false);
            ScreenUtils.setScreenBrightness(curBrightness, ComicReadActivity.this);
            SettingManager.getInstance().saveComicReadBrightness(curBrightness);
        }
    }

    @Override
    public void onClick() {
        toggleReadBar();
    }

    @Override
    public void onFling() {
        hideReadBar();
    }

    @Override
    public void showKMImgList(List<String> imgList, boolean isPreSection) {
        totalPages.setText(1 + "/" + imgList.size());
        mReadingPostionSeekBar.setMax(imgList.size() - 1);
        mPrePostion = mCurrSectionPosition - 1;
        mNextPostion = mCurrSectionPosition + 1;
        mPresenter.saveReadingSection(mComicId, mComicTitle, mComicCover, mSectionBean);
        mComicAdapter.addRefresh(imgList);
        mAdapter.notifyDataSetChanged();
//        if (isFirst) {
//            LogUtils.e("showImageList");
//            ToastUtils.getToast("replace",Toast.LENGTH_SHORT).show();
//            mPagerAdapter.replaceAll(imgList, null, false);
//            isFirst = false;
//        }

//        galleryPager.setCurrentItem(1, false);
//        galleryPager.setLocked(false);
        hideLoading();
        mReadingPostionSeekBar.setEnabled(true);
    }

    @Override
    public void showImgList(List<ComicSectionDetail> imgList, boolean isPreSection) {
//        totalPages.setText(1+"/"+imgList.size());
//        mReadingPostionSeekBar.setMax(imgList.size()-1);
//        mPrePostion = mCurrSectionPosition -1;
//        mNextPostion = mCurrSectionPosition + 1;
//        mPresenter.saveReadingSection(mComicId,mComicTitle,mComicCover,mSectionBean);
//        mComicAdapter.addRefresh(imgList);
//        mAdapter.notifyDataSetChanged();
//        hideLoading();
//        mReadingPostionSeekBar.setEnabled(true);
    }

    @Override
    public void showLoadingView() {
        showLoading();
    }

    @Override
    public void onPreSection() {
        mReadingPostionSeekBar.setEnabled(false);
        mCurrSectionPosition = mPrePostion;
        if (mCurrSectionPosition >= 0) {

            mComicAdapter.clear();
            mAdapter.notifyDataSetChanged();
            mSectionBean = mSections.get(mCurrSectionPosition);
            mPresenter.getImageUrl(mSectionBean, true);
        } else {
            ToastUtils.getSingleToast("已经是第一篇啦", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onNextSection() {
        mReadingPostionSeekBar.setEnabled(false);
        mCurrSectionPosition = mNextPostion;
        if (mCurrSectionPosition < mSections.size()) {

            mSectionBean = mSections.get(mCurrSectionPosition);
            mComicAdapter.clear();
            mAdapter.notifyDataSetChanged();
            mPresenter.getImageUrl(mSectionBean, false);
        } else {
            ToastUtils.getSingleToast("已经是最后一篇啦", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showError() {
        hideLoading();
        if (mComicAdapter.getItemCount() <= 0) {
            showLoadingError();
        }
    }

    @Override
    public void complete() {
        hideLoading();
        hideLoadingError();
    }

    @OnClick(R.id.rlt_loading_error)
    public void reTry() {
        mPresenter.getImageUrl(mSectionBean, false);
        hideLoadingError();
    }

    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (seekBar.getId() == seekbarLightness.getId() && fromUser) {
                ScreenUtils.setScreenBrightness(progress, ComicReadActivity.this);
                SettingManager.getInstance().saveComicReadBrightness(progress);
                cbVolume.setChecked(false);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    private class ChechBoxChangeListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.getId() == cbVolume.getId()) {
                if (isChecked) {

                    SettingManager.getInstance().saveSystemBrightness(true);
                    SettingManager.getInstance().removeComicReadBrightness();
                    int brightness = SettingManager.getInstance().getComicReadBrightness();
                    ScreenUtils.setScreenBrightness(brightness, ComicReadActivity.this);
                    seekbarLightness.setProgress(brightness);
                } else {
                    SettingManager.getInstance().saveSystemBrightness(false);
                }
            }
        }
    }
}
